/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-roadSOS
*
* @File name : RoadSosService.java
*
* @Author : Administrator
*
* @Date : 2017年5月12日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年5月12日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.roadSOS.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yonyou.gmmc.service.roadSOS.constant.RoadSOSConstant;
import com.yonyou.gmmc.service.roadSOS.dao.TmDealerMapper;
import com.yonyou.gmmc.service.roadSOS.dao.TtSoshelpMapper;
import com.yonyou.gmmc.service.roadSOS.model.DealerDto;
import com.yonyou.gmmc.service.roadSOS.model.StatusDto;
import com.yonyou.gmmc.service.roadSOS.model.TmDealer;
import com.yonyou.gmmc.service.roadSOS.model.TtSoshelp;
import com.yonyou.gmmc.service.roadSOS.model.TypeDto;

/**
 * @author Administrator 
 * @date 2017年5月12日
 */

@Service
@Transactional
public class RoadSosService {

    private static Logger            logger = LoggerFactory.getLogger(RoadSosService.class);
    
    private static String 			 IllegalCharacter = "|,<,>,$,&,%,script,select,alert,eval,and";

    @Autowired
    private TtSoshelpMapper          ttSoshelpMapper;

    @Autowired
    private TmDealerMapper           tmDealerMapper;
    @Value("${SMS-pass}")
    private  String smsPass;
    @Value("${SMS-key}")
    private  String smsKey;
    @Value("${SMS_CDKEY}")
    private  String SMS_CDKEY;
    @Value("${SMS_PASS}")
    private  String SMS_PASS;
    @Value("${SMS_BASEURL}")
    private  String SMS_BASEURL;

    /**
     * 道路救援
     * 
     * @author Administrator 
     * @date 2017年5月12日
     * @param ttSoshelp
     * @return
     */
    public Map<String, Object> roadsideAssistance(TtSoshelp ttSoshelp, String userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (CheckUtil.NullOrEmpty(userId)) {
                logger.info("该用户不是车主");
                result.put("flag", 2);
                result.put("msg", "请先注册会员在使用");
            } else {
                ttSoshelp.setCarOwnerUserId(Long.valueOf(userId));
                logger.info("车主ID为>>>>>>>>>>>>>>" + ttSoshelp.getCarOwnerUserId());
                logger.info("判断是否存在该救援信息");
                if (isSosHelpExistence(ttSoshelp)) {
                    logger.info("救援信息已经存在，不可重复发送救援信息。");
//                    result.put("flag", 0);
//                    result.put("msg", "救援信息已经存在，不可重复发送救援信息。");
                } else {
                    logger.info("查询用户车牌号");
                    Map<String, Object> carInfo = ttSoshelpMapper.selectCarInfo(Integer.valueOf(userId));
                    logger.info("用户信息"+carInfo);
                    String licenseNo = "";
                    if(carInfo.get("LICENSE_NO")!=null){
                    	licenseNo = carInfo.get("LICENSE_NO").toString();
                        ttSoshelp.setLicenseNo(licenseNo);
                    }
                    logger.info("不存在该救援信息，可继续发送");
                    // 生成本次订单单号
                    String oddNumber = ttSoshelpMapper.selectOrderNum(ttSoshelp);
                    ttSoshelp.setOddNumber(oddNumber);
                    logger.info("本次救援单号为：" + ttSoshelp.getOddNumber());
                    ttSoshelp.setStatus(RoadSOSConstant.SOSHELP_STATUS_SAVED);
                    logger.info("救援状态为>>>>>>>>>>>>>" + ttSoshelp.getStatus());
                    ttSoshelp.setSupportDate(DateUtil.formateDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    ttSoshelp.setCreateDate(new Date());
                    ttSoshelp.setCreateBy((long) RoadSOSConstant.OPT_USER);
                    int i = ttSoshelpMapper.insertSoshelp(ttSoshelp);
                    logger.info("新增了" + i + "条救援信息");
                    //查询该销售店的救援专员
                    String tel = ttSoshelpMapper.selectTel(ttSoshelp.getDealerCode());
                    Pattern p = Pattern.compile("1\\d{10}");
                    Matcher m = p.matcher(tel);
                    boolean b = m.matches();
                    String content = "";
                    content = content + "车主"+carInfo.get("USER_NAME")+"提交了道路救援请求，请尽快跟进处理。车主电话："+carInfo.get("PHONE");
                    if(CheckUtil.NullOrEmpty(licenseNo)){
                        content = content + "，救援地址："+ttSoshelp.getHelpLocal()+"。";
                    }else{
                        content = content + "，车牌号："+licenseNo+"，救援地址："+ttSoshelp.getHelpLocal()+"。";
                    }
//                    logger.info("短信内容为："+content);
//                    if(b){
//                        logger.info("可以发送短信");
////                        logger.info("发送短信To：" + tel);
//                        String s = SmsHttpClient.sendSms(tel, content,smsPass,smsKey,SMS_CDKEY,SMS_PASS,SMS_BASEURL);
//                        logger.info("发送短信————End");
//                        logger.info("返回码————" + s);
//                    }else{
//                        logger.info("救援专线为固定电话，不可发送短信");
//                        //result.put("flag", 0);
//                        //result.put("msg", "该店救援专线为电话，请拨打电话联系");
//                    }
                }
                result.put("flag", 1);
                result.put("msg", "您的救援位置已发送，请留意发送位置并不能保证您的救援请求及时获得响应，紧急情况下请拨打电话直接与我们联系，谢谢您的合作！");
              }
            } catch (Exception e) {
            logger.error(e.getMessage(), e);
            //result.put("flag", 0);
            //result.put("msg", "救援信息发送异常，请重试！");
        }
        return result;
    }

    /**
     * 校验救援信息是否已存在
     * 
     * @author Administrator 
     * @date 2017年5月12日
     * @param ttSoshelp
     * @return
     */
    private boolean isSosHelpExistence(TtSoshelp ttSoshelp) {
        boolean flag = false;
        logger.info("查询是否已存在该救援信息");
        List<TtSoshelp> result = ttSoshelpMapper.getSosHelp(ttSoshelp);

        if (!CheckUtil.NullOrEmpty(result)) {
            flag = true;
        }
        return flag;

    }

    /**
     * 获取最近销售店&&本市销售店
     * 
     * @author Administrator 
     * @date 2017年5月12日
     * @param ttSoshelp
     * @return
     */
    public Map<String, Object> getDealer(TtSoshelp ttSoshelp) {
        Map<String, Object> resultMap = new HashMap<>();
        List<TmDealer> firstDealer = new ArrayList<TmDealer>();
        String first = "";
        List<TmDealer> secondDealer = new ArrayList<TmDealer>();
        String second = "";
        List<TmDealer> thirdDealer = new ArrayList<TmDealer>();
        String third = "";
        logger.info("查询救援经销商信息");
        // 查最近店
        firstDealer = tmDealerMapper.selectNearDealer(ttSoshelp);
        if (firstDealer == null || firstDealer.size() == 0) {
            logger.info("没有查询到最近店");
        } else {
            first = firstDealer.get(0).getDealerCode();
            logger.info("该店为最近店>>>>>>>>>>>>" + first);
            resultMap.put("First", firstDealer.get(0));
            logger.info("最近店信息："+firstDealer.get(0).getDistance());
            //次近店
            second = firstDealer.get(1).getDealerCode();
//            logger.info("该店为次近店>>>>>>>>>>>>" + second);
            secondDealer = firstDealer;
            resultMap.put("Second", secondDealer.get(1));
            logger.info("次近店信息："+secondDealer.get(1).getDistance());
        }
        // 查首选店
        thirdDealer = tmDealerMapper.selectFirstDealer(ttSoshelp);
        if (thirdDealer == null || thirdDealer.size() == 0) {
            logger.info("没有查询到首选店");
        } else {
            third = thirdDealer.get(0).getDealerCode();
//            logger.info("该店为首选店>>>>>>>>>>>>" + third);
            if (first.equals(third)) {
                logger.info("首选店就是最近店，不显示首选店");
                //resultMap.put("First_Dealer", "");
            }else if(second.equals(third)){
                logger.info("首选店就是次近店，不显示首选店");
                //resultMap.put("First_Dealer", "");
            }else {
                logger.info("首选店不是最近店也不是次近店");
                resultMap.put("Third", thirdDealer.get(0));
            }
        }
        return resultMap;
    }

    /**
     * 更新救援状态
     * 
     * @author Administrator 
     * @date 2017年6月5日
     * @param ttSoshelp
     * @return
     * @throws Exception
     */
    public Map<String, Object> updateStatus(TtSoshelp ttSoshelp) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        // TtSoshelp params = new TtSoshelp();
        try {
            ttSoshelp.setUpdateDate(new Date());
            logger.info("更新时间为>>>>>" + ttSoshelp.getUpdateDate());
            int i = ttSoshelpMapper.updateStatus(ttSoshelp);
            logger.info(i + "条数据被更新");
            result.put("errorCode", "0");
            result.put("errorMsg", "操作成功！");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.put("errorCode", "1");
            result.put("errorMsg", "操作异常！");
        }
        return result;
    }

    /**
     * PC-道路救援查询
     * 
     * @author Administrator 
     * @date 2017年6月5日
     * @param ttSoshelp
     * @return
     * @throws Exception
     */
    public PageInfo<TtSoshelp> roadSosList(Map<String, Object> paramMap) throws Exception {
    	String c = IllegalCharacter;
		String[] characters = c.split(",");
    	for(Object o:paramMap.keySet()){
    		String key=o.toString();
    		Object valueO=paramMap.get(key);
    		if(valueO!=null && !valueO.equals("")){
    			String value=valueO.toString();
//    			logger.info("接收的参数："+value);
    			String valueLower=value.toLowerCase();
//    			logger.info("转化成小写："+valueLower);
    			for(String ct : characters){
    				if (valueLower.indexOf(ct) > -1) {
    					paramMap.put(key, "");
//    					logger.info("转化之后的参数："+paramMap.get(key));
    					break;
    				}
    			}
    		}
    	}
        List<TtSoshelp> list = new ArrayList<>();
        try {
            // 查询是否存在超过48小时未处理的救援
            List<TtSoshelp> li = ttSoshelpMapper.selectTimeOut();
            if (li.size() == 0) {
                logger.info("不存在超期未处理的订单");
            } else {
                logger.info("有超期未处理的救援单，置为已超期");
                for (int i = 0; i < li.size(); i++) {
                    TtSoshelp ttSoshelp = new TtSoshelp();
                    ttSoshelp.setStatus(10111005);
                    ttSoshelp.setOddNumber(li.get(i).getOddNumber());
                    int a = ttSoshelpMapper.updateStatus(ttSoshelp);
                    logger.info("更新数>>>>>>>" + a);
                }
            }
            // 查询PC端显示的订单
            Page<TtSoshelp> ss = PageHelper.startPage(Integer.parseInt(paramMap.get("pageNum").toString()),
                                                      Integer.parseInt(paramMap.get("pageSize").toString()));
            logger.info("ss为————" + ss);
            list = ttSoshelpMapper.selectSosList(paramMap);
//            logger.info("list为————" + list.toString());
            PageInfo<TtSoshelp> page = new PageInfo<>(list);
            logger.info("page为————" + page);
            return page;
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
    * PC-树形销售店
    * @author Administrator
    * @date 2017年6月14日
    * @return
    * @throws Exception
    */
    public List<Map<String,Object>> selectDealer() throws Exception {
        try {
            // 服务销售店列表
            logger.info("查询省份列表");
            List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
            List<DealerDto> provinceList = ttSoshelpMapper.selectProvince();
            for (int a = 0; a < provinceList.size(); a++) {
                Map<String,Object> firstMap = new HashMap<String,Object>();
                logger.info("查询城市列表");
                List<DealerDto> regionList = ttSoshelpMapper.selectCity(provinceList.get(a).getRegionCode());
                List<Map<String,Object>> reList = new ArrayList<Map<String,Object>>();
                for (int b = 0; b < regionList.size(); b++) {
                    // 查询该城市的经销商
                    List<DealerDto> dealerList = ttSoshelpMapper.selectDealer(regionList.get(b).getRegionCode());
                    logger.info(dealerList.size() + "条销售服务店");
                    Map<String,Object> secondMap = new HashMap<String,Object>();
                    if(dealerList.size()==0){
                        secondMap.put("name", regionList.get(b).getRegionName());
                        secondMap.put("id", regionList.get(b).getRegionCode());
                        secondMap.put("disabled", true);
                    }else{
                        List<Map<String,Object>> deList = new ArrayList<Map<String,Object>>();
                        for(int c=0;c<dealerList.size();c++){
                            Map<String,Object> deMap = new HashMap<String,Object>();
                            deMap.put("name", dealerList.get(c).getDealerName());
                            deMap.put("id", dealerList.get(c).getDealerCode());
                            deList.add(deMap);
                        }
                        secondMap.put("name", regionList.get(b).getRegionName());
                        secondMap.put("id", regionList.get(b).getRegionCode());
                        secondMap.put("child", deList);
                        //reList.add(secondMap);
                    }
                    reList.add(secondMap);
                }
                firstMap.put("name", provinceList.get(a).getRegionName());
                firstMap.put("id", provinceList.get(a).getRegionCode());
                firstMap.put("child", reList);
                resultList.add(firstMap);
            }
            return resultList;
        }catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }
    
    /**
    * PC-查询项
    * @author Administrator
    * @date 2017年6月14日
    * @return
    * @throws Exception
    */
    public Map<String, Object> selectList() throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            // 救援状态列表
            List<StatusDto> statusList = ttSoshelpMapper.selectStatus();
            logger.info(statusList.size() + "条救援状态");
            StatusDto e = new StatusDto();
            e.setStatusCode("");
            e.setStatusName("全部");
            statusList.add(e);
            result.put("statusList", statusList);
            // 救援方式列表
            List<TypeDto> typeList = ttSoshelpMapper.selectType();
            logger.info(typeList.size() + "条救援方式");
            TypeDto t = new TypeDto();
            t.setTypeCode("");
            t.setTypeName("全部");
            typeList.add(t);
            result.put("typeList", typeList);
            return result;
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
    * 导出查询
    * @author Administrator
    * @date 2017年6月14日
    * @param queryMap
    * @return
    * @throws Exception
    */
    public List<TtSoshelp> sosExport(Map<String, Object> queryMap) throws Exception {
        try {
            List<TtSoshelp> list = ttSoshelpMapper.selectSosList(queryMap);
            return list;
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }
    
    public String selectDealerByUserId(String userId){
        String dealerCode = "";
        dealerCode = tmDealerMapper.selectDealer(userId);
        return dealerCode;
    }
}
